<template>
    <div>
        <CategorySelect :formInline="formInline" :scencee="scencee" :getData="getData" />
        <el-card style="margin-top: 5px;">
            <div v-show="scencee">
                <el-button icon="plus" type="primary" :disabled="!formInline.category3"
                    @click="scencee = false">添加属性</el-button>
                <el-button type="danger" icon="delete" @click="deletekSelectAttr">删除</el-button>
                <el-table border stripe :data="tableData" class="table-main" @selection-change="handleSelectionChange"
                    ref="tableRef">
                    <el-table-column align="center" type="selection" width="55" />
                    <el-table-column align="center" label="序号" width="80" type="index" />
                    <el-table-column align="center" prop="attrName" label="属性名称" width="150" />
                    <el-table-column align="center" label="属性值名称">
                        <template #default="{ row }">
                            <el-tag v-for="item in row.attrValueList" :key="item.id" style="margin-left: 4px"
                                :id="item.id" :type="tagType[item.id % tagType.length]" effect="dark" round>
                                {{ item.valueName }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="操作" width="240">
                        <template #default="{ row }">
                            <el-button type="primary" icon="edit" @click="editAttr(row)">编辑</el-button>
                            <el-button type="danger" icon="delete" @click="deleteAttr(row.id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-show="!scencee">
                <el-form :model="attrFrom" :rules="rules" ref="ruleFormRef" status-icon>
                    <el-form-item prop="attrName" label="属性名称">
                        <el-input placeholder="请输入属性名称" clearable style="width:20%"
                            v-model="attrFrom.attrName"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <div style="width: 100%;">
                            <el-button icon="plus" type="primary" @click="addAttr"
                                :disabled="!attrFrom.attrName.trim()">添加属性值</el-button>
                        </div>
                        <div>
                            <el-table border stripe :data="attrFrom.attrValueList" class="attrTable">
                                <el-table-column align="center" label="序号" width="80px" type="index" />
                                <el-table-column align="center" label="属性值名称" width="400px">
                                    <template #default="{ row, $index }">
                                        <el-input v-show="row.flag" placeholder="请输入属性值名称" clearable
                                            v-model="row.valueName" :id="`input_${$index}`" @blur="inputBlure(row)" />
                                        <div v-show="!row.flag" style="text-align: left;"
                                            @click="showInput(row, $index)">{{ row.valueName }}</div>
                                    </template>
                                </el-table-column>
                                <el-table-column align="center" label="属性值操作" width="200px">
                                    <template #="{ $index }">
                                        <el-button type="danger" icon="delete"
                                            @click="attrFrom.attrValueList.splice($index, 1)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-form-item>
                </el-form>
                <el-button type="primary" @click="confirm(ruleFormRef)" :disabled="attrFrom.attrValueList.length === 0"
                    :loading="butLoading">保存</el-button>
                <el-button @click="closeAttr">取消</el-button>
            </div>
        </el-card>
    </div>
</template>

<script setup lang='ts' name="Attr">

import { getAttrInfoList, saveAttrInfo, deleteAttrInfo } from '@/api/product/attr';
import type { AttrInfo, AttrValue } from "@/api/product/attr/type"
import type { ResponseData } from "@/api/type"
import { Action, ElMessage, ElMessageBox, ElTable, FormInstance, FormRules } from 'element-plus';
import { EpPropMergeType } from 'element-plus/es/utils/index.mjs';

let butLoading = ref(false);

let tableData = ref<AttrInfo[]>();

let scencee = ref(true);

let selectIds = ref<number[]>([]);

let formInline = reactive({
    category1: undefined,
    category2: undefined,
    category3: undefined,
})

let attrFrom = reactive<AttrInfo>({
    attrName: '',
    attrValueList: [],
    categoryId: null,
    categoryLevel: null,
})

const tableRef = ref<InstanceType<typeof ElTable> | null>(null);

const rules = ref<FormRules<AttrInfo>>({
    attrName: [
        { required: true, message: '属性名称不能空', trigger: 'blur' },
    ]
});

const tagType: EpPropMergeType<StringConstructor, "primary" | "success" | "info" | "warning" | "danger", unknown>[]
    = ['primary', 'success', 'info', 'warning', 'danger']

const handleSelectionChange = (newSelection: AttrInfo[]) => {
    const validIds = newSelection
        .map(item => item.id)
        .filter(id => id !== undefined) as number[];
    selectIds.value = validIds
}


const deletekSelectAttr = () => {
    if (selectIds.value.length === 0) {
        ElMessage.error('请选择要删除的属性')
        return
    }
    ElMessageBox.confirm(
        '删除属性，将会同时删除属性值下的所有属性值，确定删除？',
        '删除提示',
        {
            distinguishCancelAndClose: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    ).then(() => {
        ElMessage.success(`删除成功[${selectIds.value.join(',')}]`)
        getData()
    }).catch((action: Action) => {
        console.log("🚀 ~ deletekSelectAttr ~ action:", action)
    })
}

const getData = (): Promise<void> | undefined => {
    if (!formInline.category1 || !formInline.category2 || !formInline.category3) {
        ElMessage.error('请选择分类')
        return
    }
    return getAttrInfoList(formInline.category1, formInline.category2, formInline.category3)
        .then((result: ResponseData<AttrInfo[]>) => {
            tableData.value = result.data
        }).catch((error: ResponseData<String>) => {
            ElMessage.error("http请求失败。" + error.message);
        });
}


let inputFlag = ref(true)
const addAttr = () => {
    // 判断是否有空的输入框
    if (attrFrom.attrValueList.some(item => item.flag)) {
        // 错误已经提示过一次，本次不再提示
        if (inputFlag.value) {
            ElMessage.error('属性值不能重复，请检查输入')
        }
        inputFlag.value = true
        // return
    } else {
        attrFrom.attrValueList.push({ valueName: '', flag: true });
    }
    // 光标移到最后一个输入框
    setTimeout(() => {
        const input = document.getElementById(`input_${attrFrom.attrValueList.length - 1}`)
        if (input) {
            input.focus()
        }
    }, 0)
}
let ruleFormRef = ref<FormInstance>();
const closeAttr = () => {
    scencee.value = true
    ruleFormRef.value?.resetFields()
    Object.assign(attrFrom, {
        attrName: '',
        attrValueList: [],
        categoryId: null,
        categoryLevel: null,
        id: null
    })
}

const scrollToLastRow = () => {
    if (tableRef.value) {
        const tableElement = tableRef.value.$el;
        const rows = tableElement.querySelectorAll('tr'); // 获取所有行
        const lastRow = rows[rows.length - 1]; // 最后一行
        if (lastRow) {
            tableRef.value.setScrollTop(lastRow.offsetTop + lastRow.offsetHeight)// 设置当前行
        }
    }
};
const confirm = async (ruleFormRef: FormInstance | undefined) => {
    if (!ruleFormRef) return
    let valid = await ruleFormRef.validate((valid, fields) => {
        if (!valid) {
            console.log('error submit!', fields);
            return;
        }
    })

    if (!valid) {
        return;
    }
    if (attrFrom.attrValueList.some(item => item.flag)) {
        ElMessage.error('属性值不能重复')
        return
    }

    // if (attrFrom.attrValueList.some(item => !item.valueName.trim())) {
    //     ElMessage.error('属性值不能为空')
    //     return
    // }
    attrFrom.categoryId = formInline.category3 as unknown as number
    attrFrom.categoryLevel = 3

    attrFrom.attrValueList = attrFrom.attrValueList.map(item => {
        // 解构赋值，排除 flag 属性
        const { flag, ...rest } = item;
        // 返回不包含 flag 的新对象
        return rest;
    });
    butLoading.value = true;
    let str = attrFrom.id ? '更新' : '新增';
    saveAttrInfo(attrFrom).then(() => {
        ElMessage.success(str + '成功');
        closeAttr()
        getData()?.then(() => {
            if (str === '新增') {
                scrollToLastRow()
            }
        });
    }).catch((error: ResponseData<String>) => {
        ElMessage.error((str + '失败。') + error.message);
    }).finally(() => {
        butLoading.value = false;
    })
}

const inputBlure = (row: AttrValue) => {
    if (row.valueName.trim() === '') {
        ElMessage.error('属性值不能为空');
        attrFrom.attrValueList = attrFrom.attrValueList.filter(item => item.valueName.trim() !== '');
    } else if (attrFrom.attrValueList.filter(item => item.valueName.trim() === row.valueName.trim()).length > 1) {
        inputFlag.value = false;
        ElMessage.error('属性值不能为重复');
    } else {
        row.flag = false;
    }
}

const showInput = (row: AttrValue, $index: number) => {
    row.flag = true;
    setTimeout(() => {
        const input = document.getElementById(`input_${$index}`)
        if (input) {
            input.focus()
        }
    }, 0)
}

const editAttr = (row: AttrInfo) => {
    scencee.value = false
    Object.assign(attrFrom, JSON.parse(JSON.stringify(row)))
}

const deleteAttr = (id: number) => {
    ElMessageBox.confirm('删除属性，将会同时删除属性值下的所有属性值，确定删除?', '删除提醒')
        .then(() => {
            deleteAttrInfo(id).then(() => {
                ElMessage.success('删除成功');
                getData()
            }).catch((error: ResponseData<Object>) => {
                ElMessage.error('删除失败。' + error.message);
            })
        }).catch((action: Action) => {
            console.log("🚀 ~ deleteAttr ~ action:", action)

        })
}
</script>

<style scoped lang='scss'>
.table-main {
    height: calc(100vh - $base-tabbar-height - var(--card-height) - 145px);
    margin: 10px 0px;
}

.attrTable {
    width: 680px;
    height: calc(100vh - $base-tabbar-height - var(--card-height) - 236px);
    margin-top: 10px;
}
</style>